package com.yumeng.webapp.shiro.controller;

import com.yumeng.common.api.ApiResult;
import com.yumeng.common.auth.BaseAuthHelper;
import com.yumeng.common.auth.BaseAuthInfo;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author wxd
 * @date 2025/9/22 15:42
 */
@Slf4j
@RestController
//@ApiSupport(order = 1)
@Tag(name = "ShiroController", description = "Shiro接口集合")
@RequestMapping("/shiro")
public class ShiroController {

    /**
     * 测试Subject与AuthInfo的转化
     *
     * @return
     */
    @GetMapping("/testSubjectToAuthInfo.vw")
    public ApiResult testSubjectToAuthInfo(){
        Subject subject = SecurityUtils.getSubject();
        Object obj = subject.getPrincipal();

        log.info("++++++++++++++++++++++++++++++++++");
        log.info("BaseAuthInfo:{}", BaseAuthInfo.class.getClassLoader());
        log.info("SecurityUtils:{}", SecurityUtils.getSubject().getPrincipal().getClass().getClassLoader());
        log.info("++++++++++++++++++++++++++++++++++");

        BaseAuthInfo authInfo = (BaseAuthInfo)obj;
        subject.getSession().setAttribute("authInfo",authInfo);
        return ApiResult.successData(authInfo);
    }

    /**
     * 测试user级别页面
     *
     * @return
     */
    @RequestMapping("/testUserLevelPage.vw")
    public ModelAndView testUserLevelPage(){
        Map<String, Object> map = new HashMap<>();
        map.put("remoteUser", BaseAuthHelper.getCurrAuthInfo().getAuthKey());
        return new ModelAndView("/test/test_user_level_page", map);
    }


    @GetMapping("/sessionView.do")
    public Collection sessionView(){
        Collection<Session> sessions = null;
        SecurityManager securityManager = SecurityUtils.getSecurityManager();
        if (securityManager instanceof DefaultSecurityManager){
            SessionManager sessionManager = ((DefaultSecurityManager) securityManager).getSessionManager();
            if (sessionManager instanceof DefaultSessionManager){
                SessionDAO sessionDAO = ((DefaultSessionManager)sessionManager).getSessionDAO();
                if (sessionDAO != null){
                    sessions = sessionDAO.getActiveSessions();
                }
            }
        }
        return sessions;
    }


}
